package com.migraine.controller;

import com.alibaba.fastjson.JSONObject;
import com.migraine.model.Rooms;
import com.migraine.model.Users;
import com.migraine.service.RoomsService;
import com.migraine.service.UsersService;
import com.migraine.websocket.WebSocketServer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Semaphore;

@Controller
@ResponseBody
@RequestMapping("/index")
public class IndexController {

    @Autowired
    private RoomsService roomsService;

    @Autowired
    private UsersService usersService;

    // 创建房间的资源包
    Semaphore createRoomSep = new Semaphore(1);

    private Random rand = new Random();

    // 日志工具
    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    /**
     * 获取房间信息列表
     *
     * @return json
     */
    @GetMapping("/getRoomsList")
    public List<Rooms> getRoomsList() {
        return roomsService.getAllRooms();
    }

    /**
     * 带参数进入房间，请求格式/index/enterRoom?roomId=房间号
     *
     * @param roomId 房间号
     * @return json {uid, roomId, secret}
     */
    @GetMapping("/enterRoom")
    public String enterRoom(@RequestParam Integer roomId) {
        //通过shiro框架获取用户保存在server的uid（通过session保存）
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String uid = (String) session.getAttribute("uid");

        Rooms room = roomsService.getRoomsById(roomId);

        logger.info("用户ID为:" + uid + "请求进入房间,房间号为" + roomId + room.toString());

        JSONObject json = new JSONObject();
        json.put("uid", uid);
        json.put("roomId", roomId);
        json.put("secret", room.getSecret());
        json.put("type", room.getType());
        json.put("roomname", room.getRoomname());
        return json.toJSONString();
    }

    @PostMapping("/verifyRoomPassword")
    public String verifyRoomPassword(@RequestBody Map<String, String> map) {
        String roomId = map.get("roomId");
        String roomPassword = map.get("roomPassword");
        String password = roomsService.getRoomPasswordById(roomId);
        JSONObject json = new JSONObject();
        if (password != null && password.equals(roomPassword)) {
            //密码正确
            json.put("msg", true);
        } else {
            json.put("msg", false);
        }
        return json.toJSONString();
    }

    /**
     * 创建房间
     *
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping("/createroom")
    public String createroom(@RequestBody Map<String, String> map) {

        boolean tmp = false;
        int availablePermits = createRoomSep.availablePermits();
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String uid = (String) session.getAttribute("uid");
        String roomname = map.get("roomname");
        int upperlimits = Integer.parseInt(map.get("upperlimits"));
        // 0是语音房间 1是视频房间
        int type = Integer.parseInt(map.get("type"));
        int secret = Integer.parseInt(map.get("secret"));
        String password = map.get("password");
        String time = map.get("createtime");
        Date date = new Date(Long.parseLong(time));
        // 随机生成房间id
        int roomid = rand.nextInt();
        while (roomsService.getRoomsById(roomid) != null || roomid < 0) {
            roomid = rand.nextInt();
        }
        if (availablePermits > 0) {
            try {
                createRoomSep.acquire(1);
                tmp = roomsService.insertRoom(roomid, roomname, uid, date, upperlimits, type, password, secret);

            } catch (InterruptedException e) {
                logger.error("错误：", e);

                Thread.currentThread().interrupt();
            } finally {
                createRoomSep.release(1);
            }
        }
        JSONObject json = new JSONObject();
        if (tmp) {
            // 0代表成功注册
            json.put("er", "0");
            json.put("roomid", roomid);
            return json.toJSONString();
        }
        // 1代表注册失败
        json.put("er", "1");
        return json.toJSONString();
    }


    /**
     * 获得头像和名字
     *
     * @return
     */
    @GetMapping("/personalInfo")
    public String personalInfo() {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String uids = (String) session.getAttribute("uid");
        int uid = Integer.parseInt(uids);
        Users user = usersService.getUsers(uid);
        String name = user.getUsername();
        String photo = user.getUserimage();
        JSONObject json = new JSONObject();
        json.put("name", name);
        json.put("photo", photo);
        json.put("uid", uids);
        return json.toJSONString();
    }

    /**
     * 判断私密房间的密码
     *
     * @param map
     * @return
     */
    @PostMapping("/judgeRoomPwd")
    public String judgeRoomRwd(@RequestBody Map<String, String> map) {
        String roomId = map.get("roomId");
        String pwd = map.get("pwd");
        String roompwd = roomsService.getRoomPasswordById(roomId);
        String er = "0";
        if (roompwd != null) {
            if (pwd.equals(roompwd)) {
                // 密码正确设置er为2
                er = "2";
            } else {
                // 密码错误设置er为1
                er = "1";
            }
        }
        JSONObject json = new JSONObject();
        json.put("er", er);
        return json.toJSONString();
    }

    /**
     * 别人点击邀请链接
     *
     * @param roomId 想要进入的房间
     * @return 首页网址加房间号
     */
    @GetMapping("/invite")
    public void invite(@RequestParam String roomId, HttpServletResponse resp) {
        try {
            resp.sendRedirect("/views/index.html?roomId=" + roomId);
        } catch (IOException e) {
            logger.error("错误：", e);
        }
    }


}
